package znet

import (
	"bytes"
	"encoding/binary"
	"errors"
	"tcpChat/conf"
	"tcpChat/ziface"
)

type DataPack struct {

}

//创建DataPack
func NewDataPack() *DataPack{
	return &DataPack{}
}

func (d *DataPack) GetHeadLen() uint32{
	//message的数据长度（int32）4字节，message的ID（int32）4字节，
	return 8
}


func (d *DataPack) Pack(message ziface.IMessage) ([]byte, error){

	buf := bytes.NewBuffer([]byte{})

	if err := binary.Write(buf, binary.BigEndian, message.GetDataLen());err != nil{
		return nil, err
	}

	if err := binary.Write(buf,binary.BigEndian, message.GetMSGId()); err!= nil{
		return nil, err
	}

	if err := binary.Write(buf, binary.BigEndian, message.GetData()); err != nil{
		return nil, err
	}

	return buf.Bytes(),nil
}

func (d *DataPack) UnPack(data []byte) (ziface.IMessage,error){
	binaryBuffer := bytes.NewReader(data)
	message := &Message{}

	//根据数据类型获取字节流的长度
	if err := binary.Read(binaryBuffer, binary.BigEndian, &message.DataLen); err != nil{
		return nil, err
	}

	if err := binary.Read(binaryBuffer, binary.BigEndian, &message.Id); err != nil{
		return nil, err
	}

	//判断数据的长度
	if conf.GlobalObject.MaxPacketSize <= 0 && message.GetDataLen() > conf.GlobalObject.MaxPacketSize{
		return nil, errors.New("字节流数据过大")
	}

	return message,nil

	//message.Data = make([]byte, message.GetDataLen())
	//
	//if err := binary.Read(binaryBuffer, binary.BigEndian, message.Data); err != nil{
	//
	//}
}